package com.supplychain.scm.core.common.validator;


import com.supplychain.scm.core.common.exception.CheckedException;
import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author liyang
 * @version 1.0.0
 * @ClassName ValidationUtils
 * @Description 参数校验工具类
 * @createTime 11:25:00 2022/04/09
 */
@UtilityClass
public class ValidationUtils {

	private Validator validator;

	static {
		validator = Validation.buildDefaultValidatorFactory().getValidator();
	}

	/**
	 * 手机号格式验证
	 */
	private final Pattern MOBILE_PATTERN = Pattern.compile("^1[3456789][0-9]{9}$");
	public boolean isPhone(String src) {
		return pattern(MOBILE_PATTERN,src);
	}

	/**
	 * 邮箱格式验证
	 */
	private final Pattern MAILBOX_PATTERN = Pattern.compile("^[\\w-.]+@([\\w-]+\\.)+[\\w-]{2,4}$");
	public boolean isMailbox(String src) {
		return pattern(MAILBOX_PATTERN,src);
	}

	/**
	 * QQ号码格式验证
	 */
	private final Pattern QQ_CODE_PATTERN = Pattern.compile("(^[1-3]{1}\\d{4,9}$)|(^[1-9]{1}\\d{4,8}$)");
	public boolean isQqCode(String src) {
		return pattern(QQ_CODE_PATTERN,src);
	}

	/**
	 * 微信号码格式验证
	 */
	private final Pattern WECHAT_PATTERN = Pattern.compile("^[a-zA-Z]([-_a-zA-Z0-9]{5,19})$");
	public boolean isWechat(String src) {
		return pattern(WECHAT_PATTERN,src);
	}

	/**
	 * 数字加字母 1-32位
	 */
	private final Pattern NUMBER_LETTER_PATTERN = Pattern.compile("^(?!.*@.*@)(?!.*\\..*\\.)[0-9A-Za-z@.]{1,32}$");
	public boolean isNumberLetter(String src) {
		return pattern(NUMBER_LETTER_PATTERN,src);
	}

	private boolean pattern(Pattern pattern,String src) {
		if(StringUtils.isEmpty(src)) {
			return false;
		}
		Matcher matcher = pattern.matcher(src);
		return matcher.matches();
	}
	/**
	 * 校验对象
	 * @param object        待校验对象
	 * @param groups        待校验的组
	 * @throws CheckedException  校验不通过，则报BaseException异常
	 */
	public void validateEntity(Object object, Class<?>... groups) throws CheckedException {
		Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
		if (!constraintViolations.isEmpty()) {
			StringBuilder msg = new StringBuilder();
			for(ConstraintViolation<Object> constraint:  constraintViolations){
				msg.append(constraint.getMessage()).append("<br>");
			}
			throw new CheckedException(msg.toString());
		}
	}
}
